<template>
  <div id="manageQuestionView">
    <div class="table_content">
      <a-table
        :ref="tableRef"
        :columns="columns"
        :data="dataList"
        :pagination="{
          showTotal: true,
          pageSize: searchParams.pageSize,
          current: searchParams.current,
          total
        }"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <!-- 操作列模板 -->
        <template #optional="{ record }">
          <a-space>
            <a-button type="primary" @click="doUpdate(record)">修改</a-button>
            <a-button status="danger" @click="doDelete(record)">删除</a-button>
          </a-space>
        </template>

        <!-- 判题配置模板 -->
        <template #judgeConfig="{ record }">
          <div v-if="record.judgeConfig">
            <div>时间: {{ record.judgeConfig.timeLimit || 0 }}ms</div>
            <div>内存: {{ record.judgeConfig.memoryLimit || 0 }}KB</div>
            <div>堆栈: {{ record.judgeConfig.stackLimit || 0 }}KB</div>
          </div>
          <span v-else>无配置</span>
        </template>

        <!-- 判题用例模板 -->
        <template #judgeCase="{ record }">
          <div v-if="record.judgeCase && record.judgeCase.length > 0">
            共 {{ record.judgeCase.length }} 个用例
          </div>
          <span v-else>无用例</span>
        </template>

        <!-- 标签模板 -->
        <template #tags="{ record }">
          <a-tag
            v-for="(tag, index) in record.tags"
            :key="index"
            color="blue"
            style="margin-right: 5px"
          >
            {{ tag }}
          </a-tag>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { Question, QuestionControllerService } from '../../../generated'
import message from '@arco-design/web-vue/es/message'
import { onBeforeRouteUpdate, useRouter } from 'vue-router'
import { Input } from '@arco-design/web-vue'

const router = useRouter()
const tableRef = ref()
const dataList = ref<any[]>([])
const total = ref(0)
const searchParams = ref({
  pageSize: 2,
  current: 1
})

const loadData = async () => {
  try {
    const res = await QuestionControllerService.listQuestionByPageUsingPost(
      searchParams.value
    )

    if (res.code === 0 && res.data) {
      // 处理数据：解析 JSON 字符串字段
      dataList.value = res.data.records.map((item: any) => {
        // 安全解析 JSON 字段的辅助函数
        const safeParse = (str: any, defaultValue: any) => {
          if (typeof str === 'string') {
            try {
              return JSON.parse(str)
            } catch (e) {
              console.warn('JSON 解析失败:', str)
              return defaultValue
            }
          }
          return str || defaultValue
        }

        return {
          ...item,
          createTime: item.createTime.slice(0, 10),
          tags: safeParse(item.tags, []),
          judgeConfig: safeParse(item.judgeConfig, {}),
          judgeCase: safeParse(item.judgeCase, [])
        }
      })
      total.value = res.data.total
    } else {
      message.error(`加载失败: ${res.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('请求异常:', error)
    message.error('网络请求异常')
  }
}

// 列配置
const columns = [
  { title: 'ID', dataIndex: 'id', width: 200 },
  { title: '标题', dataIndex: 'title', ellipsis: true },
  { title: '内容', dataIndex: 'content', ellipsis: true },
  {
    title: '标签',
    slotName: 'tags',
    width: 150
  },
  { title: '提交数', dataIndex: 'submitNum', width: 100 },
  { title: '通过数', dataIndex: 'acceptedNum', width: 100 },
  {
    title: '判题配置',
    slotName: 'judgeConfig',
    width: 150
  },
  {
    title: '测试用例',
    slotName: 'judgeCase',
    width: 200
  },
  { title: '创建时间', dataIndex: 'createTime', width: 250 },
  {
    title: '操作',
    slotName: 'optional',
    width: 150,
    fixed: 'right'
  }
]

// 删除题目
const doDelete = async (question: Question) => {
  try {
    const res = await QuestionControllerService.deleteQuestionUsingPost({
      id: question.id
    })

    if (res.code === 0) {
      message.success('删除成功')
      loadData()
    } else {
      message.error(`删除失败: ${res.message}`)
    }
  } catch (error) {
    console.error('删除异常:', error)
    message.error('删除操作异常')
  }
}

// 更新题目
const doUpdate = (question: Question) => {
  router.push({
    path: '/update/question',
    query: { id: question.id }
  })
}

//当点击页号时,触发事件
const handlePageChange = (page: any) => {
  searchParams.value.current = page
  loadData()
}

//当点击页面大小时,触发事件
const handlePageSizeChange = (size: any) => {
  console.log(size)
}

// 初始化加载数据
onMounted(() => loadData())
</script>

<style scoped>
#manageQuestionView {
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: center;
}

.table_content {
  width: 90%;
}

/* 优化表格行高 */
:deep(.arco-table-tr) {
  height: 60px;
}
</style>
